package me.alide.modules.survey.controller;

import com.alibaba.fastjson.JSON;
import me.alide.common.utils.R;
import me.alide.modules.sys.entity.SysUserEntity;
import me.alide.modules.sys.service.SysUserRoleService;
import me.alide.modules.sys.service.SysUserService;
import me.alide.modules.sys.service.SysUserTokenService;
import me.alide.modules.wechart.cp.config.WxCpConfiguration;
import me.alide.modules.wechart.cp.config.WxCpProperties;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author wutairui
 * Created on 2020/4/2.
 */
@Controller
public class WeChatController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserTokenService sysUserTokenService;

    @Autowired
    WxCpProperties wxCpProperties;

    @Autowired
    SysUserRoleService sysUserRoleService;


    Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("login/{agentId}")
    public String login( @PathVariable Integer agentId, String returnUrl) throws WxErrorException, UnsupportedEncodingException {
         WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
         String redirect = wxCpService.getOauth2Service().buildAuthorizationUrl(URLEncoder.encode(returnUrl, "utf-8"),null);
         logger.info("redirect==" + redirect );
         return "redirect:" + redirect;
    }

    @RequestMapping("auth")
    public void auth(@RequestParam("code") String code, HttpServletResponse response) throws WxErrorException, IOException {
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpProperties.getAppConfigs().get(0).getAgentId());
        WxCpOauth2UserInfo oauth2UserInfo =  wxCpService.getOauth2Service().getUserInfo(code);
        String userId = oauth2UserInfo.getUserId();
        logger.debug("userId==" + userId);
        String deviceId = oauth2UserInfo.getDeviceId();
        logger.debug("deviceId==" + deviceId);
        logger.debug("openId==" + oauth2UserInfo.getOpenId());
        logger.debug("UserTicket==" + oauth2UserInfo.getUserTicket());
        WxCpUser user = wxCpService.getUserService().getById(userId);
        System.out.println(JSON.toJSONString(user));
//        SysUserEntity sysUser = sysUserService.queryByUserName(user.getUserId());
        SysUserEntity sysUser = sysUserService.queryByUserName("jishukaifa");
        R token = sysUserTokenService.createToken(sysUser.getUserId());
        Cookie cookie = new Cookie("token", token.get("token").toString());
        cookie.setMaxAge(1000);
        response.addCookie(cookie);
        response.sendRedirect("index.html");
    }

    @ResponseBody
    @GetMapping("WW_verify_5QUm6xfBfg8yh7Gq.txt")
    public String oAuth2() {
        return  "5QUm6xfBfg8yh7Gq";
    }

}
